package JDBC.Day07;

import java.sql.*;
import java.util.HashMap;

/**
 *  事务 案例 -- 转账
 *      account表中有张三和李四两人
 *      张三给李四转账500元
 */
public class TestDemo {
    public static void main(String[] args) {
        Connection conn = null;
        PreparedStatement pstmt1 = null;
        PreparedStatement pstmt2 = null;
        PreparedStatement pstmt3 = null;
        ResultSet resultSet = null;
        HashMap<String, Double> map = new HashMap<>();

        try {
            //1. 创建连接
            conn = JDBCUtils.getConnection();

            // 开启事务
            conn.setAutoCommit(false);

            //2. 定义查询语句 -- 查询表中所有数据 效率低下
            String sql = "select * from account";
            //3. 传入sql语句并创建执行对象
            pstmt1 = conn.prepareStatement(sql);
            //4. 执行sql
            resultSet = pstmt1.executeQuery();
            //5. 获取表中所有数据并存入HashMap中
            while(resultSet.next()) {
                String name  = resultSet.getString("name");
                double balance = resultSet.getDouble("balance");
                map.put(name, balance);
            }
            //6. 获取发款人余额
            double senderBalance = map.get("张三");
            //7. 获取收款人余额
            double resiverBalance = map.get("李四");
            senderBalance -= 500;
            if(senderBalance < 0) {
                // 当付款人余额小于0时，抛出余额不足异常
                throw new RuntimeException("Out of the balance");
            }
            resiverBalance += 500;


            String setSql1 = "update account set balance = ? where name = ?";
            pstmt2 = conn.prepareStatement(setSql1);
            pstmt2.setString(1, Double.toString(senderBalance));
            pstmt2.setString(2, "张三1");
            int rs2 = pstmt2.executeUpdate();

            String setSql2 = "update account set balance = ? where name = ?";
            pstmt3 = conn.prepareStatement(setSql2);
            pstmt3.setString(1, Double.toString(resiverBalance));
            pstmt3.setString(2, "李四");
            int rs3 = pstmt3.executeUpdate();

            if(rs2 != 0 && rs3 != 0) {
                System.out.println("修改成功");
                System.out.println("张三余额：" + senderBalance);
                System.out.println("李四余额：" + resiverBalance);
            } else {
                // 如果有一个结果返回值为0，表示修改失败
                // 抛出异常
                throw new RuntimeException("Something is going wrong");
            }

            // 提交事务
            conn.commit();

        } catch (Exception e) {
            System.out.println("修改失败");

            // 事务回滚
            try {
                if(conn != null) {
                    conn.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }

            e.printStackTrace();
        } finally {
            JDBCUtils.close(resultSet, pstmt1, conn);
            JDBCUtils.close(pstmt2, null);
            JDBCUtils.close(pstmt3, null);
        }
    }
}
